<template>
  <div class="token-list-page">
    <div class="page-header">
      <h1>我的令牌</h1>
      <button @click="handleCreate" class="btn btn-primary">+ 添加令牌</button>
    </div>
    
    <div class="search-bar">
      <input
        v-model="searchQuery"
        type="text"
        class="form-input"
        placeholder="🔍 搜索令牌..."
        @input="handleSearch"
      />
      <select v-model="filterCategory" @change="handleFilter" class="form-select">
        <option value="">全部分类</option>
        <option v-for="cat in categories" :key="cat" :value="cat">{{ cat }}</option>
      </select>
    </div>
    
    <div v-if="tokenStore.tokens.length === 0 && !tokenStore.loading" class="empty-state">
      <div class="empty-icon">🔐</div>
      <h3>还没有令牌</h3>
      <p>添加你的第一个2FA令牌来开始使用</p>
      <button @click="handleCreate" class="btn btn-primary">+ 添加令牌</button>
    </div>
    
    <div class="tokens-grid" v-else-if="!tokenStore.loading">
      <div v-for="token in tokenStore.tokens" :key="token.id" class="token-card">
        <div class="token-header">
          <div class="token-service">
            <strong>{{ token.serviceName }}</strong>
            <span v-if="token.accountName" class="token-account">{{ token.accountName }}</span>
          </div>
          <button
            @click="toggleFavorite(token.id)"
            class="favorite-btn"
            :class="{ active: token.isFavorite }"
            title="收藏"
          >
            {{ token.isFavorite ? '⭐' : '☆' }}
          </button>
        </div>
        
        <div v-if="token.category" class="token-category">
          📁 {{ token.category }}
        </div>
        
        <div v-if="token.notes" class="token-notes">
          📝 {{ truncateNotes(token.notes) }}
        </div>
        
        <div class="token-actions">
          <button @click="generateCode(token)" class="btn btn-primary btn-sm">
            🔑 生成验证码
          </button>
          <button @click="editToken(token)" class="btn btn-sm">✏️ 编辑</button>
          <button @click="deleteToken(token.id)" class="btn btn-danger btn-sm">🗑️ 删除</button>
        </div>
      </div>
    </div>
    
    <div v-else class="loading">
      <div class="spinner"></div>
      <p>加载中...</p>
    </div>
    
    <!-- 创建/编辑对话框 -->
    <TokenForm
      v-if="showFormDialog"
      :token="editingToken"
      @close="handleCloseForm"
      @submit="handleSubmitForm"
    />
    
    <!-- 验证码显示对话框 -->
    <CodeDisplay
      v-if="showCodeDialog"
      :code="currentCode"
      :token="currentToken"
      :loading="codeLoading"
      :error="codeError"
      @close="handleCloseCode"
      @copy="handleCodeCopied"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useTokenStore } from '@/store/tokens';
import { useUserStore } from '@/store/user';
import TokenForm from '@/components/TokenForm.vue';
import CodeDisplay from '@/components/CodeDisplay.vue';

const tokenStore = useTokenStore();
const userStore = useUserStore();

const searchQuery = ref('');
const filterCategory = ref('');
const showFormDialog = ref(false);
const showCodeDialog = ref(false);
const editingToken = ref(null);
const currentCode = ref(null);
const currentToken = ref(null);
const codeLoading = ref(false);
const codeError = ref('');

const categories = computed(() => {
  const cats = new Set();
  tokenStore.tokens.forEach(token => {
    if (token.category) cats.add(token.category);
  });
  return Array.from(cats);
});

function truncateNotes(notes) {
  if (!notes) return '';
  return notes.length > 100 ? notes.substring(0, 100) + '...' : notes;
}

function handleCreate() {
  editingToken.value = null;
  showFormDialog.value = true;
}

function editToken(token) {
  editingToken.value = token;
  showFormDialog.value = true;
}

function handleCloseForm() {
  showFormDialog.value = false;
  editingToken.value = null;
}

async function handleSubmitForm(formData) {
  try {
    if (editingToken.value) {
      // 更新令牌
      await tokenStore.updateToken(editingToken.value.id, formData);
      alert('令牌更新成功！');
    } else {
      // 创建新令牌
      await tokenStore.createToken(formData);
      alert('令牌添加成功！');
    }
    handleCloseForm();
  } catch (error) {
    alert('操作失败: ' + (error.response?.data?.error?.message || error.message));
  }
}

async function generateCode(token) {
  const password = prompt('请输入您的密码以生成验证码：');
  if (!password) return;
  
  currentToken.value = token;
  currentCode.value = null;
  codeError.value = '';
  codeLoading.value = true;
  showCodeDialog.value = true;
  
  try {
    const codeData = await tokenStore.generateCode(token.id, password);
    currentCode.value = codeData;
  } catch (error) {
    codeError.value = error.response?.data?.error?.message || '生成失败，请检查密码';
  } finally {
    codeLoading.value = false;
  }
}

function handleCloseCode() {
  showCodeDialog.value = false;
  currentCode.value = null;
  currentToken.value = null;
  codeError.value = '';
}

function handleCodeCopied() {
  // 验证码已复制
}

async function toggleFavorite(id) {
  try {
    await tokenStore.toggleFavorite(id);
  } catch (error) {
    alert('操作失败');
  }
}

async function deleteToken(id) {
  if (!confirm('确定要删除这个令牌吗？此操作不可恢复。')) return;
  
  try {
    await tokenStore.deleteToken(id);
    alert('令牌已删除');
  } catch (error) {
    alert('删除失败');
  }
}

function handleSearch() {
  if (searchQuery.value) {
    tokenStore.searchTokens(searchQuery.value, filterCategory.value);
  } else {
    handleFilter();
  }
}

function handleFilter() {
  if (filterCategory.value) {
    tokenStore.fetchTokens({ category: filterCategory.value });
  } else {
    tokenStore.fetchTokens();
  }
}

onMounted(() => {
  tokenStore.fetchTokens();
  userStore.fetchCategories();
});
</script>

<style scoped>
.token-list-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 40px 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.page-header h1 {
  font-size: 32px;
  color: var(--text-color, #333);
}

.search-bar {
  display: flex;
  gap: 12px;
  margin-bottom: 30px;
}

.form-input {
  flex: 1;
  padding: 12px 16px;
  border: 1px solid var(--border-color, #d1d5db);
  border-radius: 8px;
  font-size: 15px;
  color: var(--text-color, #333);
  background: var(--bg-color, #fff);
}

.form-select {
  min-width: 150px;
  padding: 12px 16px;
  border: 1px solid var(--border-color, #d1d5db);
  border-radius: 8px;
  font-size: 15px;
  color: var(--text-color, #333);
  background: var(--bg-color, #fff);
  cursor: pointer;
}

.empty-state {
  text-align: center;
  padding: 80px 20px;
}

.empty-icon {
  font-size: 80px;
  margin-bottom: 20px;
}

.empty-state h3 {
  font-size: 24px;
  color: var(--text-color, #333);
  margin-bottom: 12px;
}

.empty-state p {
  font-size: 16px;
  color: var(--text-secondary, #6b7280);
  margin-bottom: 24px;
}

.tokens-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
}

.token-card {
  background: var(--bg-color, #fff);
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.token-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.token-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.token-service strong {
  display: block;
  font-size: 18px;
  color: var(--text-color, #333);
}

.token-account {
  display: block;
  font-size: 14px;
  color: var(--text-secondary, #6b7280);
  margin-top: 4px;
}

.favorite-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  opacity: 0.4;
  transition: opacity 0.2s;
}

.favorite-btn:hover {
  opacity: 0.7;
}

.favorite-btn.active {
  opacity: 1;
}

.token-category {
  font-size: 13px;
  color: var(--text-secondary, #6b7280);
  margin-bottom: 8px;
  padding: 4px 8px;
  background: var(--bg-secondary, #f3f4f6);
  border-radius: 4px;
  display: inline-block;
}

.token-notes {
  font-size: 14px;
  color: var(--text-secondary, #6b7280);
  margin-bottom: 16px;
  padding: 10px;
  background: var(--bg-secondary, #f9fafb);
  border-radius: 6px;
  border-left: 3px solid var(--primary-color, #3b82f6);
  line-height: 1.5;
}

.token-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.btn {
  padding: 10px 18px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.btn-primary {
  background: var(--primary-color, #3b82f6);
  color: white;
}

.btn-primary:hover {
  background: var(--primary-dark, #2563eb);
}

.btn-sm {
  padding: 8px 14px;
  font-size: 13px;
}

.btn-danger {
  background: #ef4444;
  color: white;
}

.btn-danger:hover {
  background: #dc2626;
}

.loading {
  text-align: center;
  padding: 60px 20px;
}

.spinner {
  width: 40px;
  height: 40px;
  margin: 0 auto 16px;
  border: 4px solid var(--bg-secondary, #f3f4f6);
  border-top-color: var(--primary-color, #3b82f6);
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.loading p {
  color: var(--text-secondary, #6b7280);
}

/* 响应式 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .search-bar {
    flex-direction: column;
  }
  
  .form-select {
    width: 100%;
  }
  
  .tokens-grid {
    grid-template-columns: 1fr;
  }
  
  .token-actions {
    flex-direction: column;
  }
  
  .token-actions .btn {
    width: 100%;
  }
}

/* 深色模式 */
.dark-theme .token-card {
  background: #1f2937;
}

.dark-theme .form-input,
.dark-theme .form-select {
  background: #111827;
  border-color: #374151;
  color: #e5e7eb;
}

.dark-theme .token-category {
  background: #374151;
}

.dark-theme .token-notes {
  background: #111827;
  border-left-color: #2563eb;
}
</style>


